<script setup lang="ts">
import { reqGetUser } from '@/apis/hospital';
import type { UserResponseData, UserArr } from '@/apis/hospital/type';
import { reqAddOrUpdateUser, reqCertationType, reqCity, reqRemoveUser } from '@/apis/user';
import { AddOrUpdateUser, CertationArr, CertationTypeResponseData } from '@/apis/user/type';
import { Delete, User } from '@element-plus/icons-vue';
import { CascaderProps, ElMessage } from 'element-plus';
import { watch } from 'vue';
import { onMounted, reactive, ref } from 'vue';
import { useRoute, useRouter } from 'vue-router';

const $router = useRouter()
const $route = useRoute()
const userArr = ref<UserArr>([])
const scene = ref<number>(0)
const certationArr = ref<CertationArr>([])
const userParams = reactive<AddOrUpdateUser>({
  name: '',
  certificatesType: '',
  certificatesNo: '',
  sex: 0,
  birthdate: '',
  phone: '',
  isMarry: 0,
  isInsure: 0,
  addressSelected: [],
  address: '',
  contactsName: '',
  contactsCertificatesType: '',
  contactsCertificatesNo: '',
  contactsPhone: ''
})

onMounted(() => {
  getAllUser()
  getCertationType()
  if ($route.query.type === 'add') {
    scene.value = 1
  }

  if ($route.query.type === 'edit') {
    scene.value = 1
  }
})

const getAllUser = async () => {
  const res: UserResponseData = await reqGetUser()
  if (res.code === 200) {
    userArr.value = res.data
  }
}

const changeScene = (user: AddOrUpdateUser) => {
  reset()
  scene.value = 1
  Object.assign(userParams, user)
}

const getCertationType = async () => {
  const res: CertationTypeResponseData = await reqCertationType()
  if (res.code === 200) {
    certationArr.value = res.data
  }
}

const props: CascaderProps = {
  lazy: true,
  async lazyLoad(node: any, resolve: any) {
    const res: any = await reqCity(node.data.id || "86")
    const showData = res.data.map((item: any) => {
      return {
        id: item.id,
        value: item.value,
        label: item.name,
        leaf: !item.hasChildren
      }
    })
    resolve(showData)
  }
}

const submit = async () => {
  try {
    await reqAddOrUpdateUser(userParams)
    ElMessage({
      type: 'success',
      message: userParams.id ? '修改成功' : '添加成功'
    })

    if ($route.query.type) {
      $router.back()
    } else {
      scene.value = 0
    }
    getAllUser()
  } catch (error) {
    ElMessage({
      type: 'success',
      message: userParams.id ? '修改失败' : '添加失败'
    })
  }
}

const reset = () => {
  Object.assign(userParams, {
    name: null,
    certificatesType: '',
    certificatesNo: '',
    sex: 0,
    birthdate: '',
    phone: '',
    isMarry: 0,
    isInsure: 0,
    addressSelected: [],
    address: '',
    contactsName: '',
    contactsCertificatesType: '',
    contactsCertificatesNo: '',
    contactsPhone: ''
  })
}

const removeUser = async(id:any) => {
  try {
    await reqRemoveUser(id)
    getAllUser()
    ElMessage({
      type:'success',
      message:'删除成功'
    })
  } catch (error) {
    ElMessage({
      type:'success',
      message:'删除失败'
    })
  }
}


const backPatient = () => {
  scene.value = 0
}

watch(() => userArr.value, () => {
  if ($route.query.type === 'edit') {
    const user = userArr.value.find((item: any) => {
      return item.id == $route.query.id
    })
    console.log(user)
    Object.assign(userParams, user)
  }
})
</script>



<template>
  <el-card class="box-card">
    <template #header>
      <div class="card-header">
        <span @click="backPatient">就诊人管理</span>
        <el-button type="primary" size="default" :icon="User" style="background-color: #28d17c"
          @click="changeScene">添加就诊人</el-button>
      </div>
    </template>
    <div class="visitor" v-if="scene === 0">
      <visitor class="item" v-for="(user, index) in userArr" :key="user.id" :user="user" :index="index"
        @changeScene="changeScene">
        <template v-slot:buttons>
          <el-popconfirm :title="`你确定要删除${user.name}吗?`" @confirm="removeUser(user.id)">
            <template #reference>
              <el-button circle type="danger" size="default" :icon="Delete"></el-button>
            </template>
          </el-popconfirm>
        </template>
      </visitor>

    </div>
    <div class="form" v-else>
      <el-divider contentt-position="center">就诊人信息</el-divider>
      <el-form style="width: 60%;margin: 10px auto;">
        <el-form-item label="用户姓名">
          <el-input placeholder="请您输入用户姓名" v-model="userParams.name"></el-input>
        </el-form-item>
        <el-form-item label="证件类型">
          <el-select placeholder="请你选择证件的类型" style="width: 100%" v-model="userParams.certificatesType">
            <el-option v-for="item in certationArr" :label="item.name" :key="item.id" :value="item.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="证件号码">
          <el-input placeholder="请你输入证件号码" v-model="userParams.certificatesNo"></el-input>
        </el-form-item>
        <el-form-item label="用户性别">
          <el-radio-group v-model="userParams.sex">
            <el-radio :label="1">男</el-radio>
            <el-radio :label="0">女</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="出生日期">
          <el-date-picker value-format="YYYY-MM-DD" v-model="userParams.birthdate" type="date" placeholder="请你选择日期" />
        </el-form-item>
        <el-form-item label="手机号码">
          <el-input placeholder="请你输入用户手机号码" v-model="userParams.phone"></el-input>
        </el-form-item>
      </el-form>
      <el-divider content-position="center">建档信息（完善后部分医院首次就诊不排队建档）</el-divider>
      <el-form style="width: 60%; margin: 10px auto">
        <el-form-item label="婚姻状况">
          <el-radio-group v-model="userParams.isMarry">
            <el-radio :label="1">已婚</el-radio>
            <el-radio :label="0">未婚</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="自费/医保">
          <el-radio-group v-model="userParams.isInsure">
            <el-radio :label="1">自费</el-radio>
            <el-radio :label="0">医保</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="当前的住址" v-model="userParams.addressSelected">
          <el-cascader :props="props" />
        </el-form-item>
        <el-form-item label="详细地址">
          <el-input placeholder="请你输入用户详细地址" v-model="userParams.address"></el-input>
        </el-form-item>
      </el-form>
      <el-divider content-position="center">联系人信息（选填）</el-divider>
      <el-form style="width: 60%; margin: 10px auto" label-width="80">
        <el-form-item label="用户姓名">
          <el-input placeholder="请你输入用户姓名" v-model="userParams.contactsName"></el-input>
        </el-form-item>
        <el-form-item label="证件类型">
          <el-select placeholder="请你选择证件的类型" style="width: 100%">
            <el-option v-for="item in certationArr" :label="item.name" :key="item.id" :value="item.value"
              v-model="userParams.contactsCertificatesType"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="证件号码">
          <el-input placeholder="请你输入证件号码" v-model="userParams.contactsCertificatesNo"></el-input>
        </el-form-item>
        <el-form-item label="手机号码">
          <el-input placeholder="请你输入用户手机号码" v-model="userParams.contactsPhone"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" size="default" @click="submit">提交</el-button>
          <el-button type="primary" size="default" @click="reset">重写</el-button>
        </el-form-item>
      </el-form>
    </div>
  </el-card>
</template>



<style scoped lang="scss">
.box-card {
  margin-top: 30px;

  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;

    span{
      cursor: pointer;
    }
    span:hover{
      color: #55a6fe;
    }
  }

  .visitor {
    display: flex;
    flex-wrap: wrap;

    .item {
      width: 32.5%;
      margin: 10px 7px 0 0;
    }
  }
}
</style>